<?php

namespace App\Http\Controllers\Home\Index\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Goods;
use App\Model\Gprice;
use App\Model\Gshow;
use App\Model\Gdescr;
use Illuminate\Support\Facades\Redis; 

/**
 * @author wuboheng
 * 此类用于把热卖top30商品存入Redis
 */
class HotDataLoad extends Controller
{
    public function loadHotData()
    {   

        //查询top30商品的ID
        $topID = Goods::orderBy('sales', 'desc')
            ->limit(30)
            ->pluck('id');

        // dd($topID);
        
        //用于存放热卖商品的数据
        $hotInfo = [];

        //遍历top30的gid,把相关信息查询出来并且放入$hotInfo
        foreach ($topID as $gid) {
            // echo $gid.',';
            //查询goods表
            $good = Goods::select(['id', 'goods_sn', 'gname', 'price', 'unit', 'sales', 'click', 'pic', 'is_member_price', 'score', 'state'])
                ->where('id', $gid)
                ->first()
                ->toArray();

            $hotInfo['goods'] = $good;

            //查询goods_price表
            $good_price = Gprice::select(['id', 'price', 'discount_price', 'storage', 'size', 'color', 'sales', 'is_discount', 'state'])
                ->where('gid', $gid)
                ->get()
                ->toArray();

            $hotInfo['goods_price'] = $good_price;

            //处理goods_price数据,以用于商品详情页遍历颜色,尺寸,价格之间的笛卡尔关系
            $relation = new \stdClass();
            foreach ($good_price as $v) {

                $key = $v['color'] . '_' . $v['size'];
                $key = urldecode($key);
                $relation->$key['pirce'] = $v['discount_price'];
                $relation->$key['mktprice'] = $v['price'];
                $relation->$key['storage'] = $v['storage'];
                $relation->$key['id'] = $v['id'];

            }

            $hotInfo['relation'] =  urldecode(json_encode($relation));


            //查询goods_show表
            $good_pic = Gshow::select(['id', 'path', 'state', 'descr'])
                ->where('gid', $gid)
                ->get()
                ->toArray();

            $hotInfo['goods_pic'] = $good_pic;


            //查询goods_descr表
            $good_descr = Gdescr::select(['descr'])
                ->where('gid', $gid)
                ->where('state', 1)
                ->value('descr');


            $hotInfo['descr'] = $good_descr;

            // dd($hotInfo);
            
            //以哈希类型,存入Redis. key为hotData, field为hotData:$gid
            Redis::hSet('hotData', 'hotData:'.$gid, json_encode($hotInfo));
            Redis::expire('hotData', 60*60*24);  //有效期为1天

        }

        // dd($hotInfo);

    }


}
